const express = require("express")
const router = express.Router();
const passport = require("passport")
const mongoose = require('mongoose')
var ArticleCate = require('../../models/ArticleCate');
var profile = require('../../models/Profile');
// 新增和修改
router.post('/', (req, res) => {
    console.log(req.params.id);
    const pro = {};
    if (req.body.title) pro.title = req.body.title;
    if (req.body.descripton) pro.descripton = req.body.descripton;
    new ArticleCate(pro).save()
        .then(ArticleCate => {
            res.json(ArticleCate)
        })
})
router.post('/:id', (req, res) => {
        console.log(req.params.id);
        const pro = {};
        if (req.body.title) pro.title = req.body.title;
        ArticleCate.findOneAndUpdate({ _id: req.params.id }, { $set: pro }, { new: true }).then(ArticleCate => res.json(ArticleCate))
    })
    //GET api/ArticleCate  获取数据
const data = [{ title: 'Node' }, { title: 'MYSQL' }, { title: 'HTML' }, { title: 'JavaScript' }, { title: 'MongDB' }, { title: "CSS" }]
router.get('/', (req, res) => {
        ArticleCate.find().then(ArticleCate => {
            if (ArticleCate) {
                res.json(ArticleCate)
            } else {
                res.status(404).json('没有内容')
            }
        })
    })
    //GET api/profil：id 获取 某一条数据
router.get('/:id', (req, res) => {
        ArticleCate.findOne({ _id: req.params.id }).then(ArticleCate => {
            if (ArticleCate) {
                res.json(ArticleCate)
            } else {
                res.status(404).json('没有内容')
            }
        })
    })
    //DELETE api/profil/delete 删除某一条数据
router.delete('/:id', (req, res) => {
        console.log(req.params.id);

        ArticleCate.findOneAndRemove({ _id: req.params.id }).then(ArticleCate => {
                res.status(200).json('ok')
            })
            .catch(err => res.status(404).json(err))
    })
    //GET api/cate 获得某个分类的文章文章 传分类的id 获得的数据
router.get('/cate/:id', (req, res) => {
    console.log(req.params.id);

    ArticleCate.aggregate([{
            $lookup: {
                from: "profiles",
                localField: "_id",
                foreignField: "cid",
                as: "articleData"
            }
        },
        {
            $match: {
                _id: mongoose.Types.ObjectId(req.params.id)
            }
        }

    ]).then(resdata => {
        const data = JSON.stringify(resdata);
        const items = resdata[0]
        console.log(items.articleData);
        res.json(items.articleData)

    }).catch(err => {
        res.status(404).json(err)
    })
})


module.exports = router;